package cn.kooki.app.duobao.ui.Fragment.duobaorecord;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseFragment;
import cn.kooki.app.duobao.base.BaseRecyclerAdapter;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.Index.GoodsItem;
import cn.kooki.app.duobao.data.Bean.Index.IndexGoodResponse;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.User.record.RecordItem;
import cn.kooki.app.duobao.data.Bean.User.record.RecordResponse;
import cn.kooki.app.duobao.data.bus.ChangePageEvent;
import cn.kooki.app.duobao.data.constant.Constants;
import cn.kooki.app.duobao.ui.Activity.Comm.RootAcitivity;
import cn.kooki.app.duobao.ui.Activity.Goods.GoodsDetailAcitvity;
import cn.kooki.app.duobao.ui.Activity.Goods.OrderCodeListActivity;
import cn.kooki.app.duobao.ui.Adapter.DuobaoRecordAdapter;
import cn.kooki.app.duobao.ui.Adapter.ListRecommAdapter;
import cn.kooki.app.duobao.ui.view.CustomRefreshHeader;
import cn.kooki.app.duobao.ui.view.LoadMoreContainer;
import cn.kooki.app.duobao.ui.view.LoadMoreHandler;
import cn.kooki.app.duobao.ui.view.LoadMoreListViewContainer;
import cn.kooki.app.duobao.ui.widget.CustomRelativeLayout;
import cn.kooki.app.duobao.util.ObjectUtils;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.manager.AppManager;
import cn.kooki.app.duobao.util.manager.ShopCartManager;
import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiong on 2015/12/13.
 */
public class DuobaoRecordItemFragment extends BaseFragment implements View.OnClickListener {
    public final static int ALL_TYPE = 0;
    public final static int CURRT_TYPE = 1;
    public final static int RESULT_TYPE = 2;
    @Bind(R.id.blank_go_duobao)
    Button blankGoDuobao;
    @Bind(R.id.layout_empty)
    LinearLayout layoutEmpty;
    @Bind(R.id.list_recommend)
    RecyclerView listRecommend;
    @Bind(R.id.list_view)
    ListView listView;
    @Bind(R.id.load_more_content_container)
    LoadMoreListViewContainer loadMoreContentContainer;
    @Bind(R.id.swipe_refresh_layout)
    PtrFrameLayout swipeRefreshLayout;
    @Bind(R.id.loading_wrapper)
    CustomRelativeLayout loadingWrapper;
    @Bind(R.id.emptyWrapper)
    ScrollView emptyWrapper;

    private int type;
    private int page = 1;

    private UserInfo userinfo;
    private String user_id;
    private boolean isother;
    private ListRecommAdapter listRecommAdapter;
    private DuobaoRecordAdapter adapter;

    @Override
    public View setView(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.blank_duobao_record, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void afterView() {
        Bundle arguments = getArguments();
        type = arguments.getInt("type", ALL_TYPE);
        user_id = arguments.getString("uid");
        userinfo = SharePreferencesUtils.getUserinfo(context);
        if (TextUtils.isEmpty(user_id)) {
            isother = false;
            user_id = userinfo.getUid();
        } else {
            isother = true;
        }
        swipeRefreshLayout.setVisibility(View.VISIBLE);
        loadingWrapper.setVisibility(View.VISIBLE);
        loadingWrapper.showloading();
        emptyWrapper.setVisibility(View.GONE);
        loadingWrapper.setRetryClickListener(new CustomRelativeLayout.onRetryClickListener() {
            @Override
            public void onRetry() {
                loadingWrapper.hideNetError();
                swipeRefreshLayout.autoRefresh(false);
            }
        });
        blankGoDuobao.setOnClickListener(this);
        CustomRefreshHeader refreshHeader = new CustomRefreshHeader(context);
        swipeRefreshLayout.addPtrUIHandler(refreshHeader);
        swipeRefreshLayout.setHeaderView(refreshHeader);
        swipeRefreshLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, listView, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getdata(false);
            }
        });
        loadMoreContentContainer.setAutoLoadMore(true);
        loadMoreContentContainer.setShowLoadingForFirstPage(true);
        loadMoreContentContainer.useDefaultFooter();
        loadMoreContentContainer.setLoadMoreHandler(new LoadMoreHandler() {
            @Override
            public void onLoadMore(LoadMoreContainer loadMoreContainer) {
                getdata(true);
            }
        });
        listRecommend.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        listRecommAdapter = new ListRecommAdapter(context);
        listRecommend.setAdapter(listRecommAdapter);
        listRecommAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Object data) {
                GoodsItem item = (GoodsItem) data;
                Intent intent = new Intent(context, GoodsDetailAcitvity.class);
                intent.putExtra("id", item.getId());
                intent.putExtra("qishu", item.getQishu());
                context.startActivity(intent);
            }
        });

        adapter = new DuobaoRecordAdapter(context, datas, isother);
        adapter.setOnClickWithTypeListener(new DuobaoRecordAdapter.RecordOnClickWithTypeListener() {
            @Override
            public void onItemClick(int position, int type) {
                RecordItem recordItem = datas.get(position);
                if (type == 0) {
                    ShopCartManager.getInstance().addShopCart(recordItem);
                    ChangePageEvent pageEvent = new ChangePageEvent();
                    pageEvent.item = 3;
                    EventBus.getDefault().post(pageEvent);
                    AppManager.getAppManager().getTopWith(RootAcitivity.class);
                } else {
                    Intent intent = new Intent(context, OrderCodeListActivity.class);
                    intent.putExtra("item", recordItem);
                    intent.putExtra("uid", user_id);
                    startActivity(intent);
                }
            }
        });
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RecordItem recordItem = datas.get(position);
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("id", recordItem.id);
                params.put("qishu", recordItem.qishu);
                intent(GoodsDetailAcitvity.class, params);
            }
        });
        getdata(false);
        gettuijian();
    }


    /**
     * 获取推荐商品
     */
    private void gettuijian() {
        MainFactory.getApiInstance().tuijianlist(new Callback<IndexGoodResponse>() {
            @Override
            public void success(IndexGoodResponse indexGoodResponse, Response response) {
                if (indexGoodResponse.getData() != null) {
                    listRecommAdapter.mDatas.clear();
                    listRecommAdapter.addDatas(indexGoodResponse.getData());
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }


    public ArrayList<RecordItem> datas = new ArrayList<>();


    private void getdata(final boolean isloadmore) {
        if (!isloadmore) {
            page = 1;
        } else {
            page++;
        }

        MainFactory.getApiInstance().listduobaorecord(user_id, type, page, new Callback<RecordResponse>() {
            @Override
            public void success(RecordResponse baseResponse, Response response) {

                if (baseResponse.data != null) {
                    if (!isloadmore) {
                        datas.clear();
                    }
                    datas.addAll(baseResponse.data);
                    if (datas.size() == 0) {
                        emptyWrapper.setVisibility(View.VISIBLE);
                        loadingWrapper.setVisibility(View.GONE);
                    } else {
                        emptyWrapper.setVisibility(View.GONE);
                        loadingWrapper.setVisibility(View.VISIBLE);
                    }
                    adapter.notifyDataSetChanged();
                    finishloadMore(baseResponse.data);
                } else {
                    finishloadError();
                }
                hideloading();
            }

            @Override
            public void failure(RetrofitError error) {
                if (datas.size() == 0 && emptyWrapper != null) {
                    emptyWrapper.setVisibility(View.VISIBLE);
                    loadingWrapper.setVisibility(View.GONE);
                } else if (emptyWrapper != null) {
                    emptyWrapper.setVisibility(View.GONE);
                    loadingWrapper.setVisibility(View.VISIBLE);
                }
                if (error.getKind() == RetrofitError.Kind.NETWORK && loadingWrapper != null) {
                    loadingWrapper.showNetError();
                }
                hideloading();
                finishloadError();
            }
        });
    }

    private void hideloading() {
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.refreshComplete();
            loadingWrapper.hideloading();
        }
    }

    private void finishloadMore(ArrayList<RecordItem> datas) {
        if (loadMoreContentContainer != null) {
            loadMoreContentContainer.loadMoreFinish(this.datas.size() == 0, datas.size() == Constants.DEFAULT_COUNT);
        }
    }

    private void finishloadError() {
        if (loadMoreContentContainer != null) {
            loadMoreContentContainer.loadMoreError(200, "网络错误,请重试");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onClick(View v) {
        if (v == blankGoDuobao) {
            ChangePageEvent pageEvent = new ChangePageEvent();
            pageEvent.item = 0;
            EventBus.getDefault().post(pageEvent);
        }
    }
}
